
//  PanResonder和Animation的结合使用
import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    Animated,
    Easing,
    PanResponder,
    TouchableOpacity,
    LayoutAnimation,
    TouchableHighlight,
    ToastAndroid,
    Platform,
    UIManager
} from 'react-native';

const SQUARE_DIMENSIONS = 100;// 方块的大小

export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pan:new Animated.ValueXY()
        };
        this.myPanResponder={}  //你自定义的触摸事件集合
    }

    getStyle=()=> {
        return [styles.square,
            {
                transform: this.state.pan.getTranslateTransform()
            }
        ]
    }

    componentWillMount() {
        this.myPanResponder = PanResponder.create({

            // 按击的时候是否要求成为响应者：
            onStartShouldSetPanResponder: (evt, gestureState) => true,
            // 按击事件劫持，是否把事件向子组件传递
            onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
            // 移动的时候是否要成为事件响应者
            onMoveShouldSetPanResponder: (evt, gestureState) => true,
            // 移动事件劫持，是否把事件向子组件传递
            onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
            // 当有另一个组件要求成为事件响应者的时候，是否要释放响应者
            onPanResponderTerminationRequest: (evt, gestureState) => true,

            //响应对应事件后的处理:
            onPanResponderGrant: (evt, gestureState) => {
                this.state.pan.setOffset({x: this.state.pan.x.getAnimatedValue(), y: this.state.pan.y.getAnimatedValue()});
                this.state.pan.setValue({x: 0, y: 0}); //Initial value
            },
            onPanResponderMove: Animated.event([
                null, {dx: this.state.pan.x, dy: this.state.pan.y}
            ]), // Creates a function to handle the movement and set offsets
            onPanResponderRelease: (evt, gestureState) => {
                this.state.pan.flattenOffset(); //
            },
            onPanResponderTerminate: (evt, gestureState) => {
                this.setState( {eventName:'另一个组件已经成为了新的响应者'} )
            }
        });
    }

    render() {
        return (
            <View style={styles.container}>
                <Animated.View style={this.getStyle()}  {...this.myPanResponder.paHandlers} />
            </View>

        )}

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center'
    },
    square: {
        width: SQUARE_DIMENSIONS,
        height: SQUARE_DIMENSIONS,
        backgroundColor: 'blue'
    }
});